package com.service.tools.componets;

import com.service.tools.inter.NoAuth;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        
        // 检查是否需要跳过验证
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 如果方法上有@NoAuth注解，则跳过验证
            if (handlerMethod.getMethod().isAnnotationPresent(NoAuth.class)) {
                return true;
            }
        }
        
        // 获取token并验证
        String token = request.getHeader("Authorization");
        if (token == null || !isValidToken(token)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        
        return true;
    }
    
    private boolean isValidToken(String token) {
        // 实现token验证逻辑
        return true;
    }
}
